<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data1: { type: Object as () => any, required: true },
    data2: { type: Object as () => any, default: [] },
    data3: { type: Object as () => any, default: [] },
    data4: { type: Object as () => any, default: [] },
    data5: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    title: { type: String, default: '' },
    dataName: { type: Object as () => any, default: [] },
    // max: { type: Number, default: 250000 },
    // min: { type: Number, default: 0 },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;
  const barWidth = 16; // 控制柱子宽度
  const colors = ['#ff9c39', '#029cc7', '#91cc75', '#f9a04b', '#7266ba'];

  const buildOption = (): any => {
    const datasets = [props.data1 ?? [], props.data2 ?? [], props.data3 ?? [], props.data4 ?? [], props.data5 ?? []];
    const names = (props.dataName as any[]) || [];
    const series: any[] = [];

    datasets.forEach((dataArr, index) => {
      if (Array.isArray(dataArr) && dataArr.length > 0) {
        const baseSeries: any = {
          name: names[index] ?? `系列${index + 1}`,
          type: 'bar',
          barGap: 1,
          barWidth,
          barMaxWidth: barWidth,
          data: dataArr, // 使用传入的实际数据
          itemStyle: {
            color: colors[index],
            borderRadius: [8, 8, 8, 8],
            opacity: 0.9,
          },
        };
        series.push(baseSeries);
      }
    });

    return {
      title: {
        text: props.title,
        left: 'center',
        top: '3%',
        textStyle: {
          fontSize: 14,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        appendToBody: true,
        axisPointer: { type: 'shadow' },
      },
      bar: {
        barGap: '30%',
        barCategoryGap: '60%',
      },
      legend: {
        data: names,
        top: props.title === '' ? '0%' : '12%',
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '5%',
        top: '30%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: props.datax ?? [],
        axisTick: { alignWithLabel: true },
      },
      yAxis: {
        type: 'value',
        axisLabel: { formatter: '{value}' },
        splitLine: { show: true },
      },
      series,
    };
  };

  const initCharts = () => {
    try {
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
      }
      if (chartInstance) {
        chartInstance.setOption(buildOption(), true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    if (chartInstance) {
      chartInstance.setOption(buildOption(), true);
    }
  };

  const handleResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  onMounted(async () => {
    await nextTick();
    initCharts();
    window.addEventListener('resize', handleResize);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    chartInstance?.dispose();
    chartInstance = null;
  });

  watch(
    () => [props.title, props.dataName, props.datax, props.data1, props.data2, props.data3, props.data4, props.data5],
    () => updateChart(),
    { deep: false }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
